import axios from 'axios';
import { AIProvider } from '@/types';
import { DEFAULT_AI_PROVIDER } from '@/constants/ai-config';

export class AIService {
  private provider: AIProvider;

  constructor(provider: AIProvider = DEFAULT_AI_PROVIDER) {
    this.provider = provider;
  }

  /**
   * 调用AI接口生成内容
   */
  async generateContent(prompt: string): Promise<string> {
    try {
      // 尝试使用不同的AI服务
      return await this.callHuggingFaceAPI(prompt);
    } catch (error) {
      console.error('AI服务调用失败:', error);
      // 如果AI服务失败，返回模拟生成的内容
      return this.generateFallbackContent(prompt);
    }
  }

  /**
   * 调用Hugging Face免费API
   */
  private async callHuggingFaceAPI(prompt: string): Promise<string> {
    try {
      const response = await axios.post(
        `${this.provider.baseUrl}/models/microsoft/DialoGPT-medium`,
        {
          inputs: prompt,
          parameters: {
            max_length: this.provider.maxTokens,
            temperature: 0.7,
            top_p: 0.95,
            do_sample: true
          }
        },
        {
          headers: {
            'Content-Type': 'application/json',
            // 如果有API密钥的话
            ...(this.provider.apiKey && { 'Authorization': `Bearer ${this.provider.apiKey}` })
          },
          timeout: 30000
        }
      );

      if (response.data && response.data[0] && response.data[0].generated_text) {
        return response.data[0].generated_text;
      }
      
      throw new Error('Invalid response format');
    } catch (error) {
      console.error('Hugging Face API调用失败:', error);
      throw error;
    }
  }

  /**
   * 调用Together AI API
   */
  private async callTogetherAPI(prompt: string): Promise<string> {
    try {
      const response = await axios.post(
        `${this.provider.baseUrl}/chat/completions`,
        {
          model: this.provider.model,
          messages: [
            {
              role: "user",
              content: prompt
            }
          ],
          max_tokens: this.provider.maxTokens,
          temperature: 0.7
        },
        {
          headers: {
            'Content-Type': 'application/json',
            ...(this.provider.apiKey && { 'Authorization': `Bearer ${this.provider.apiKey}` })
          },
          timeout: 30000
        }
      );

      if (response.data && response.data.choices && response.data.choices[0]) {
        return response.data.choices[0].message.content;
      }
      
      throw new Error('Invalid response format');
    } catch (error) {
      console.error('Together AI API调用失败:', error);
      throw error;
    }
  }

  /**
   * 备用内容生成（当AI服务不可用时）
   */
  private generateFallbackContent(prompt: string): string {
    // 简单的模板化生成，实际项目中可以使用更复杂的规则
    const templates = [
      "这是基于您原始内容的改写版本，已针对平台特性进行优化。",
      "经过平台化改写，内容更符合目标用户的阅读习惯。",
      "专为该平台定制的内容版本，突出了关键信息点。"
    ];
    
    const randomTemplate = templates[Math.floor(Math.random() * templates.length)];
    return `${randomTemplate}\n\n[由于AI服务暂时不可用，这是基于模板生成的示例内容]`;
  }

  /**
   * 检查AI服务可用性
   */
  async checkServiceHealth(): Promise<boolean> {
    try {
      await this.generateContent("测试连接");
      return true;
    } catch (error) {
      return false;
    }
  }

  /**
   * 切换AI服务提供商
   */
  switchProvider(provider: AIProvider): void {
    this.provider = provider;
  }
}

// 导出单例实例
export const aiService = new AIService();